// 用户仓库
import { defineStore } from 'pinia';
import { reqLogin } from '@/api/user';
import type { loginFormData, loginResponseData } from '@/api/user/type';
import type { UserState } from './types/type';
import { SET_TOKEN, GET_TOKEN } from '@/utils/token';

// 定义用户仓库
const useUserStore = defineStore('user', {
    state: (): UserState => {
        return {
            token: GET_TOKEN(),
        }
    },
    getters: {
    },
    actions: {
        // 用户登录
        async userLogin(data: loginFormData) {
            // 登录请求
            let result: loginResponseData = await reqLogin(data);
            // 登录成功
            if (result.code == 200) {
                // 存储token 
                this.token = result.data.token as string;
                // 由于store采用js对象模拟数据,因此还需本地存储持久化
                // localStorage.setItem('TOKEN', result.data.token as string);
                SET_TOKEN(result.data.token as string);
                // 跳转到首页
                return 'ok';
            }
            // 登录失败
            else {
                return Promise.reject(new Error(result.data.message));
            }
        }
    }

})

// 导出用户仓库
export default useUserStore;